﻿using MediatR;
using SmartProduction.Domain;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue.Interface;
using SmartProduction.Read.API.Application.Commands.BomCommand;

namespace SmartProduction.Read.API.Application.CommandHandlers.BomCommandHandler
{
    /// <summary>
    /// 处理工序列表命令
    /// </summary>
    public class ProcessInfoQueryCommandHandler : IRequestHandler<ProcessInfoQueryCommand, APIResult<APIPaing<ProcessInfo>>>
    {
        /// <summary>
        /// 工艺流程仓储
        /// </summary>
        private readonly IBaseRepository<ProcessInfo> procRepository;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="mapper">映射</param>
        /// <param name="procRepository">工艺流程仓储</param>
        public ProcessInfoQueryCommandHandler( IBaseRepository<ProcessInfo> procRepository)
        {
            this.procRepository = procRepository;
        }
        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">命令</param>
        /// <param name="cancellationToken">重置</param>
        /// <returns></returns>
        public async Task<APIResult<APIPaing<ProcessInfo>>> Handle(ProcessInfoQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPaing<ProcessInfo>> result = new APIResult<APIPaing<ProcessInfo>>();
            var entity = procRepository.GetAll().Result;
           if(request.BomId != 0)
            {
                entity=entity.Where(x=>x.BomId == request.BomId);
            }
            APIPaing<ProcessInfo> paing = new APIPaing<ProcessInfo>();
            result.Code = APIEnums.查询成功;
            result.Msg = APIEnums.查询成功.ToString();
            paing.TotalCount = entity.Count();
            paing.PageCount = (int)Math.Ceiling(paing.TotalCount * 1.0 / request.PageSize);
            paing.Items= entity.OrderByDescending(x=>x.ProcessId).Skip((request.PageIndex-1)*request.PageSize).Take(request.PageSize).ToList();
            result.data = paing;
            return await Task.FromResult(result);
        }
    }
}
